//
//  VOLOrderFormInfoViewController.m
//  Volver
//
//  Created by administrator on 14-10-20.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLOrderFormInfoViewController.h"

#import "common.h"
#import "HTTPDefine.h"

#import "REFrostedViewController.h"
#import "ASIHTTPRequest.h"
#import "JSONKit.h"
#import "MBProgressHUD.h"

#import "VOLAppDelegate.h"
#import "VOLCommentViewController.h"
#import "VOLChatViewController.h"


@interface VOLOrderFormInfoViewController ()
{
    VOLAppDelegate *del;
    JSONDecoder *jd;
    MBProgressHUD *HUD;
    NSFileManager *manager;
    
    NSDateFormatter *formatter;
    //入住按钮，放在这里声明是为了后面的更改
    UIButton *checkInBtn;
    
    //定义一个号码的字符串，以便后面使用
    NSString *landlordPhone;
    
    //定义一个整形数，保存存当前显示订单的订单号
    int currentOrderFormID;
}
@end

@implementation VOLOrderFormInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //初始化一些对象
    del = kGetDel;
    jd = [[JSONDecoder alloc] init];
    manager = [NSFileManager defaultManager];

    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    
    //添加标题
    self.title = @"订单详情";
    
    //添加返回按钮
    addBackButton();
    
    
    //设置Label上的字体颜色
    self.houseTypeAndPriceLabel.textColor = kPriceLabelColor;
    self.houseAddressLabel.textColor = kPriceLabelColor;
    self.arriveDateLabel.textColor = kOrangeColor;
    self.leaveDateLabel.textColor = kOrangeColor;
    self.landlordNameLabel.textColor = kThemeColor;
    
    //提示label隐藏
    self.noticeLabel.hidden = YES;
    //当前日期
    NSString *nowStr = [formatter stringFromDate:[NSDate date]];
    NSDate *currentDate = [formatter dateFromString:nowStr];
    double currentTime = [currentDate timeIntervalSince1970];
    
    //从“我的旅程”跳转过来时，隐藏部分控件，显示其它控件
    if (self.sourceFrom == 25) {
        self.commentLabel.hidden = YES;
        self.isCommentLabel.hidden = YES;
        
        //记录当前订单的订单号
        currentOrderFormID = self.receiveModel.orderFormID;
        
        //添加取消订单按钮
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消订单" style:UIBarButtonItemStylePlain target:self action:@selector(cnacleOrderForm:)];
        self.navigationItem.rightBarButtonItem.tintColor = kThemeColor;
        
        //如果过期没有入住，不显示入住按钮
        if (self.receiveModel.arriveDate >= currentTime) {
            //添加“入住”按钮
            checkInBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, kViewHeight - 44, kViewWidth, 44)];
            checkInBtn.backgroundColor = [UIColor colorWithRed:1 green:90.0/255 blue:95.0/255 alpha:0.9];
            [checkInBtn addTarget:self action:@selector(checkIn:) forControlEvents:UIControlEventTouchUpInside];
            [checkInBtn setTitle:@"入住" forState:UIControlStateNormal];
            [checkInBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [checkInBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
            [self.view addSubview:checkInBtn];
        }
        
        
        //加载界面内容
        [self loadOrderFormInfo];
    }
    
    //从“历史”跳转过来时，显示全部控件
    if (self.sourceFrom == 26) {
        
        //记录当前订单的订单号
        currentOrderFormID = self.historyModel.orderFormID;
        //加载界面
        [self loadOrderFormInfoFromHistory];
    }
    
    //开启交互功能（必须开启）
    self.landlordNameLabel.userInteractionEnabled = YES;
    
    //给姓名Label上加单击手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(contactLandlord:)];
    tapGesture.numberOfTapsRequired = 1;
    tapGesture.numberOfTouchesRequired = 1;
    [self.landlordNameLabel addGestureRecognizer:tapGesture];
    
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 加载数据
#pragma mark 加载整个界面数据（来自“我的旅程”）
-(void)loadOrderFormInfo{
    //先从本地查找是否已有图片
    NSString *imagePath = [NSString stringWithFormat:@"%@%d/houseImages/%d/%@",kGetDocumentsPath,del.currentUser.userID,self.receiveModel.houseID,self.receiveModel.houseImageName];
    if ([manager fileExistsAtPath:imagePath]) {
        self.houseImageView.image = [UIImage imageWithContentsOfFile:imagePath];
    }else{
        NSLog(@"没有图片");
        //若不存在，调用方法下载图片
        [del loadHeadImage:self.receiveModel.houseImageName userID:self.receiveModel.houseID headImageView:self.houseImageView imagePath:imagePath];
    }
    
    self.houseTitleLabel.text = self.receiveModel.houseTitle;
    self.houseAddressLabel.text = self.receiveModel.houseAddress;
    self.lodgerNameLabel.text = del.currentUser.userName;
    //调用方法加载部分房屋和房东的信息
    [self getPartInfoOfHouseAndLandlord:self.receiveModel.houseID];
    //调用方法加载订单分部信息
    [self getOrderFormData:self.receiveModel.orderFormID];
}

#pragma mark 加载整个界面数据（来自“历史”）
-(void)loadOrderFormInfoFromHistory{
    //先从本地查找是否已有图片
    NSString *imagePath = [NSString stringWithFormat:@"%@%d/houseImages/%d/%@",kGetDocumentsPath,del.currentUser.userID,self.historyModel.houseID,self.historyModel.houseImageName];
    if ([manager fileExistsAtPath:imagePath]) {
        self.houseImageView.image = [UIImage imageWithContentsOfFile:imagePath];
    }else{
        NSLog(@"没有图片");
        //若不存在，调用方法下载图片
        [del loadHeadImage:self.historyModel.houseImageName userID:self.historyModel.houseID headImageView:self.houseImageView imagePath:imagePath];
    }
    
    self.houseTitleLabel.text = self.historyModel.houseTitle;
    self.lodgerNameLabel.text = del.currentUser.userName;
    self.houseTypeAndPriceLabel.text = [NSString stringWithFormat:@"%@ · ￥%.1f/晚",self.historyModel.houseType,self.historyModel.housePrice];
    
    if (self.historyModel.isComment) {
        self.isCommentLabel.text = @"已评价";
        self.isCommentLabel.textColor = kPriceLabelColor;
    }else{
        self.isCommentLabel.text = @"未评价";
        self.isCommentLabel.textColor = kOrangeColor;
        //添加“前去评价”按钮
        UIButton *commentBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, kViewHeight - 44, kViewWidth, 44)];
        commentBtn.backgroundColor = [UIColor colorWithRed:1 green:90.0/255 blue:95.0/255 alpha:0.9];
        [commentBtn addTarget:self action:@selector(goToComment:) forControlEvents:UIControlEventTouchUpInside];
        [commentBtn setTitle:@"前去评价" forState:UIControlStateNormal];
        [commentBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [commentBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
        [self.view addSubview:commentBtn];
    }
    
    //调用方法加载部分房屋和房东的信息
    [self getPartInfoOfHouseAndLandlord:self.historyModel.houseID];
    //调用方法加载订单分部信息
    [self getOrderFormData:self.historyModel.orderFormID];
    
}


#pragma mark 加载部分房屋和房东的信息
-(void)getPartInfoOfHouseAndLandlord:(int)houseID{
    NSString *urlstr = [NSString stringWithFormat:@"%@orderform/getPartInfo?houseID=%d",kHTTPHome,houseID];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    NSData *data = [request responseData];
    if (data == nil) {
        NSLog(@"orderFormInfo-----partInfo---data为空");
        return;
    }
    NSDictionary *dic = [jd objectWithData:data];
    int result = [[dic objectForKey:@"result"] intValue];
    if (result == 0) {
        NSLog(@"orderFormInfo-----partInfo---查询失败");
        return;
    }
    NSArray *array = [dic objectForKey:@"partInfo"];
    NSDictionary *partInfoDic = array[0];
    
    //更新label
    
    self.landlordNameLabel.text = [partInfoDic objectForKey:@"user_name"];
    //保存房东电话，以备后面用到
    landlordPhone = [partInfoDic objectForKey:@"user_phone"];
    
    //从“我的旅程”界面跳转过来时，需要组装房屋类型和价格
    if (self.sourceFrom == 25) {
        NSString *houseType,*housePrice;
        housePrice = [partInfoDic objectForKey:@"house_price"];
        kGetHouseType(houseType, [[partInfoDic objectForKey:@"house_type"] intValue]);
        self.houseTypeAndPriceLabel.text = [NSString stringWithFormat:@"%@ · ￥%@/晚",houseType,housePrice];
    }
    
    
    //如果是从“历史”界面跳转过来，需要组装房屋地址
    if (self.sourceFrom == 26) {
        //获取房屋地址
        NSString *province = [partInfoDic objectForKey:@"house_province"];
        NSString *city = [partInfoDic objectForKey:@"house_city"];
        NSString *street = [partInfoDic objectForKey:@"house_street"];
        self.houseAddressLabel.text = [NSString stringWithFormat:@"%@%@%@",province,city,street];
    }
}

#pragma mark 加载订单数据
-(void)getOrderFormData:(int)orderFormID{
    NSString *urlstr = [NSString stringWithFormat:@"%@orderform/getOrderFormPartInfo?orderFormID=%d",kHTTPHome,orderFormID];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    NSData *data = [request responseData];
    if (data == nil) {
        NSLog(@"orderFormInfo-----OrderFormPartInfo---data为空");
        return;
    }
    NSDictionary *dic = [jd objectWithData:data];
    int result = [[dic objectForKey:@"result"] intValue];
    if (result == 0) {
        NSLog(@"orderFormInfo-----OrderFormPartInfo---查询失败");
        return;
    }
    NSArray *array = [dic objectForKey:@"orderFormPartInfo"];
    NSDictionary *partInfoDic = array[0];
    
    self.personNumLabel.text = [partInfoDic objectForKey:@"person_num"];
    self.totalPriceLabel.text = [NSString stringWithFormat:@"￥%@",[partInfoDic objectForKey:@"totle_price"]];
    
    double arriveDate,leaveDate;
    arriveDate = [[partInfoDic objectForKey:@"arrive_date"] doubleValue];
    leaveDate = [[partInfoDic objectForKey:@"leave_date"] doubleValue];
    
    self.arriveDateLabel.text = [formatter stringFromDate:kTransformToDate(arriveDate)];
    self.leaveDateLabel.text = [formatter stringFromDate:kTransformToDate(leaveDate)];
    
    //订单状态label
    if ([[partInfoDic objectForKey:@"status"] intValue]) {
        self.ofStatusLabel.text = @"已入住";
        self.ofStatusLabel.textColor = kPriceLabelColor;
    }else{
        self.ofStatusLabel.text = @"未入住";
        self.ofStatusLabel.textColor = kOrangeColor;
    }
    
}

#pragma mark - 按钮点击事件
#pragma mark 返回按钮事件
-(void)goBack:(id)sender{
    back;
}

#pragma mark 入住动作
-(void)checkIn:(id)sender{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您确定已经入住？" delegate:self cancelButtonTitle:@"不小心碰到了" otherButtonTitles:@"朕已入住", nil];
    alert.tag = 100;
    [alert show];
    
//    [self changeViewAfterCheckIn];
    
    
}

#pragma mark 前去评价按钮
-(void)goToComment:(id)sender{
    VOLCommentViewController *commentVC = [self.storyboard instantiateViewControllerWithIdentifier:@"commentController"];
    if (self.sourceFrom == 25) {
        commentVC.sourceFrom = 25;
        commentVC.houseID = self.receiveModel.houseID;
    }
    if (self.sourceFrom == 26) {
        commentVC.sourceFrom = 26;
        commentVC.houseID = self.historyModel.houseID;
    }
    [self.navigationController pushViewController:commentVC animated:YES];
}

#pragma mark 取消订单
-(void)cnacleOrderForm:(id)sender{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您确定要取消订单吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 101;
    [alert show];
}


#pragma mark - 手势处理
#pragma mark 单击手势
-(void)contactLandlord:(UITapGestureRecognizer *)recognizer{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"电话",@"聊天", nil];
    [sheet showInView:self.view];
}


#pragma mark - 其它操作
#pragma mark 入住操作成功后，界面的一些改变
-(void)changeViewAfterCheckIn{
    //移除“入住”按钮
    [checkInBtn removeFromSuperview];
    //添加“前去评价”按钮
    UIButton *commentBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, kViewHeight - 44, kViewWidth, 44)];
    commentBtn.backgroundColor = [UIColor colorWithRed:1 green:90.0/255 blue:95.0/255 alpha:0.9];
    [commentBtn addTarget:self action:@selector(goToComment:) forControlEvents:UIControlEventTouchUpInside];
    [commentBtn setTitle:@"前去评价" forState:UIControlStateNormal];
    [commentBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [commentBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [self.view addSubview:commentBtn];
    //更改导航栏左边按钮
    self.navigationItem.leftBarButtonItem = nil;
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"暂不评价" style:UIBarButtonItemStylePlain target:self action:@selector(goBack:)];
    [left setTintColor:kThemeColor];
    del.isRefresh = 5;
    self.navigationItem.leftBarButtonItem = left;
    
    //更改“订单状态”label
    self.ofStatusLabel.text = @"已入住";
    self.ofStatusLabel.textColor = kPriceLabelColor;
    
    //显示是否评价label
    self.commentLabel.hidden = NO;
    self.isCommentLabel.hidden = NO;
    self.isCommentLabel.text = @"未评价";
    self.isCommentLabel.textColor = kOrangeColor;
    
    //显示提示label
    self.noticeLabel.hidden = NO;
}

#pragma mark - 代理方法
#pragma mark alertView代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex != 1) {
        return;
    }
    
    switch (alertView.tag) {
        case 100:
        {
#pragma mark 执行入住操作
            NSLog(@"执行入住操作");
            __block BOOL isCheckIn = NO;
            
            HUD = [[MBProgressHUD alloc] initWithView:self.view];
            [self.view addSubview:HUD];
            [HUD showAnimated:YES whileExecutingBlock:^{
                //修改订单的status
                NSString *urlstr = [NSString stringWithFormat:@"%@orderform/checkInHouse?userID=%d&houseID=%d",kHTTPHome,del.currentUser.userID,self.receiveModel.houseID];
                NSURL *url = [NSURL URLWithString:urlstr];
                ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
                [request startSynchronous];
                
                NSData *data = [request responseData];
                if (data == nil) {
                    NSLog(@"orderFormInfo-----入住---data为空");
                    return;
                }
                NSDictionary *dic = [jd objectWithData:data];
                int result = [[dic objectForKey:@"result"] intValue];
                if (result) {
                    isCheckIn = YES;
                }
            } completionBlock:^{
                [HUD removeFromSuperview];
                HUD = nil;
                
                HUD = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:HUD];
                if (isCheckIn) {
                    HUD.labelText = @"入住成功";
                    HUD.mode = MBProgressHUDModeCustomView;
                    HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Checkmark.png"]];
                    self.navigationItem.rightBarButtonItem = nil;
                }else{
                    HUD.labelText = @"操作失败！";
                    HUD.mode = MBProgressHUDModeText;
                }
                [HUD showAnimated:YES whileExecutingBlock:^{
                    sleep(1);
                } completionBlock:^{
                    [HUD removeFromSuperview];
                    HUD = nil;
                    
                    //更新界面
                    [self changeViewAfterCheckIn];
                }];
                
            }];
        }
            break;
        case 101:
        {
#pragma mark 取消订单操作
            NSLog(@"取消订单操作");
            __block BOOL isCancle = NO;
            
            HUD = [[MBProgressHUD alloc] initWithView:self.view];
            [self.view addSubview:HUD];
            [HUD showAnimated:YES whileExecutingBlock:^{
                //修改订单的status
                NSString *urlstr = [NSString stringWithFormat:@"%@orderform/deleteOrderForm?orderFormID=%d",kHTTPHome,currentOrderFormID];
                
                
                NSURL *url = [NSURL URLWithString:urlstr];
                ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
                [request startSynchronous];
                
                NSData *data = [request responseData];
                if (data == nil) {
                    NSLog(@"orderFormInfo-----取消订单---data为空");
                    return;
                }
                NSDictionary *dic = [jd objectWithData:data];
                int result = [[dic objectForKey:@"result"] intValue];
                if (result) {
                    isCancle = YES;
                }
            } completionBlock:^{
                [HUD removeFromSuperview];
                HUD = nil;
                
                HUD = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:HUD];
                if (isCancle) {
                    HUD.labelText = @"已取消订单";
                    HUD.mode = MBProgressHUDModeCustomView;
                    HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Checkmark.png"]];
                }else{
                    HUD.labelText = @"操作失败！";
                    HUD.mode = MBProgressHUDModeText;
                }
                [HUD showAnimated:YES whileExecutingBlock:^{
                    sleep(1);
                } completionBlock:^{
                    [HUD removeFromSuperview];
                    HUD = nil;
                    
                    if (isCancle) {//取消成功，返回
                        del.isRefresh = 15;
                        back;
                    }
                }];
                
            }];
            
        }
            
            break;

    }
    
}

#pragma mark - ActionSheet代理
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        NSLog(@"打电话");
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",landlordPhone]]];
    }
    else if (buttonIndex == 1){
        VOLChatViewController *ct = [[VOLChatViewController alloc]initWithNibName:@"VOLChatViewController" bundle:nil];
        ct.chatToName =[  NSString stringWithFormat:@"%@@aming.local",landlordPhone] ;
        [self.navigationController pushViewController:ct animated:YES];
    }
}

@end










